package binarytree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @Author: 海琳琦
 * @Date: 2021/9/8 17:59
 * https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
 * 给定一个二叉树的根节点 root ，返回它的 中序 遍历。  左 根 右
 */
public class Title94 {
    static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(){}
        TreeNode(int val){
            this.val = val;
        }
        TreeNode(int val, TreeNode right, TreeNode left){
            this.val = val;
            this.right = right;
            this.left = left;
        }
    }

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1);
        TreeNode right = new TreeNode(2);
        right.left = new TreeNode(3);
        treeNode.right = right;
        List<Integer> integers = inorderTraversal(treeNode);
        System.out.println();
    }

    static List<Integer> list;
    private static List<Integer> inorderTraversal(TreeNode root) {
        list = new ArrayList<>();
        InOrder(root);
        return list;
    }

    /**
     * 非递归中序遍历方法
     * @param root
     */
    private static void InOrder1(TreeNode root){
        Stack<TreeNode> nodes = new Stack<>();
        while(root!=null||!nodes.isEmpty()){
            while(root!=null){
                nodes.add(root);
                root = root.left;
            }
            TreeNode top = nodes.pop();
            list.add(top.val);
            root = top.right;
        }
    }

//递归方法
    private static void InOrder(TreeNode root){
        if(root!=null){
            InOrder(root.left);
            list.add(root.val);
            InOrder(root.right);
        }
    }
}
